import json
import re
import requests
from bs4 import BeautifulSoup
import prettytable as pt
from time import sleep

url = 'https://y.qq.com/'
res = requests.get(url)
res.encoding = 'utf-8'  # 处理乱码

# 把页面源代码交给BeautifulSoup进行处理，生成bs对象
main_page = BeautifulSoup(res.text,'html.parser')  # 指定HTML解析器
alist = main_page.find("a",attrs={"title":"排行榜"})

href = 'https://y.qq.com' + alist.get('href')  # 直接通过get就可以拿到属性的值

# 拿到每一首歌的歌曲名称
ranking_res = requests.get(href)
ranking_res.encoding = 'utf-8'
ranking_res_text = ranking_res.text

obj = re.compile(r'</a><a title="(?P<name>.*?)" href="',re.S)
name_list = obj.finditer(ranking_res_text)

for name in name_list:
    s_name = name.group('name')

    url = f'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?p=1&n=10&w={s_name}'
    headers = {
        "cookie": "pgv_pvid=7501923864; fqm_pvqid=2b067c2e-dc8b-46db-b686-01f419e96ef9; ts_uid=1548710688; RK=Ht9A85OhW3; ptcz=90ac94ec68c5f48cbe1347ad9f2fb99beb6f990e4b9388b4d666266e08f1a1a0; tmeLoginType=2; euin=oKCiow4ioKSlNv**; ts_refer=ADTAGmyqq; ptui_loginuin=1632531779@qq.com; fqm_sessionid=171f8421-fc49-4e61-bffd-bc7769a48b52; pgv_info=ssid=s4646412018; _qpsvr_localtk=0.797931739028352; login_type=1; wxunionid=; qqmusic_key=Q_H_L_5uUq2f-31jSEa-cPsEnMIAmz_FKX_4e-E5tnERvZdaC9dgv0hDCGbKA; wxrefresh_token=; wxopenid=; psrf_access_token_expiresAt=1657380311; qm_keyst=Q_H_L_5uUq2f-31jSEa-cPsEnMIAmz_FKX_4e-E5tnERvZdaC9dgv0hDCGbKA; uin=1632531779; psrf_qqrefresh_token=1486244611DF6E3010B240E510415B38; qm_keyst=Q_H_L_5uUq2f-31jSEa-cPsEnMIAmz_FKX_4e-E5tnERvZdaC9dgv0hDCGbKA; psrf_qqunionid=B280ED1F61C2336D02BFBE2E4AC4EECC; psrf_musickey_createtime=1649604311; psrf_qqaccess_token=A62E68B8DE81CBD01ECDC20E4EF54A40; psrf_qqopenid=15D109AFB7C5737114CF39D7DFBFF633; ts_last=y.qq.com/n/ryqq/songDetail/000An6OI4ScInL"
        }
    res = requests.get(url,headers=headers)
    json_str = res.text
    json_ss = json_str[9:-1]
    json_dict = json.loads(json_ss)  # 变成字典格式

    # 提取歌曲信息的列表
    song_list = json_dict['data']['song']['list']
    tb = pt.PrettyTable()
    tb.field_names = ['序号','歌名','歌手','专辑']
    music_info_list = []
    count = 0
    for song in song_list:
        # 歌曲名称
        song_name = song['songname']
        # 歌曲的id
        song_mid = song['songmid']
        # 歌手名称
        singer = song['singer'][0]['name']
        # 专辑名称
        albumname = song['albumname']
        # print(singer,song_name,song_mid,albumname)
        tb.add_row([count,song_name,singer,albumname])
        music_info_list.append([song_mid,song_name,singer])
        count += 1
    # print(tb)

    input_index = 0
    download_info = music_info_list[input_index]
    # print(download_info)
    # 拿到歌曲的songmid 用来 拼接歌曲下载的url
    songmid = download_info[0]
    # 把songmid传入下载歌曲的url里
    music_info_url = 'https://u.y.qq.com/cgi-bin/musicu.fcg?data={"req":{"module":"CDN.SrfCdnDispatchServer","method":"GetCdnDispatch","param":{"guid":"7494297315","calltype":0,"userip":""}},"req_0":{"module":"vkey.GetVkeyServer","method":"CgiGetVkey","param":{"guid":"7494297315","songmid":["%s"],"songtype":[0],"uin":"1632531779","loginflag":1,"platform":"20"}},"comm":{"uin":1632531779,"format":"json","ct":24,"cv":0}}'%songmid
    # print(music_info_url)
    # 发送网络请求 需要的音乐url
    purl_data = requests.get(music_info_url,headers=headers).json()
    # 获取数据 获取里面生成的部分音乐链接 合并成音乐所在的链接
    purl = purl_data['req_0']['data']['midurlinfo'][0]['purl']
    media_url = 'https://dl.stream.qqmusic.qq.com/'+purl
    # 获取音乐的二进制数据
    music_data = requests.get(media_url).content
    # 保存数据
    with open(f'D:\\ui\\reptile\QQmusic\\{download_info[1]}.mp3','wb') as f:
        f.write(music_data)
    print(f"{download_info[1]}--->下载完成！")

res.close()
